// components/ex/ex-list/index.js
import {
  experimentSearch,
  experimentAdd
} from '../../../api/ex'
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    params: {
      name: '',
      currentPage: 1,
      size: 20
    },
    dataSource: [],
    show: false,
    dialog: {
      show: false,
      name: '',
      remark: '',
      title: '新建实验'
    }

  },
  

  /**
   * 组件的方法列表
   */
  methods: {
    onSearch(event) {
      console.log(event)
    },
    onClear() {
      console.log('clear')

    },
    fetchData() {
      experimentSearch(this.data.params, res => {
        this.setData({
          dataSource: res?.records || []
        })
      })
    },
    onDialogShow() {
      this.setData({
        dialog: {
          ...this.data.dialog,
          show: true
        }
      });
    },
    onClose() {
      this.setData({
        dialog: {
          ...this.data.dialog,
          show: false
        }
      });
    },

    onConfirm(resolve) {
      if (this.data.dialog.name) {
        experimentAdd({
          name: this.data.dialog.name,
          remark: this.data.dialog.remark
        }, this.fetchData)
        resolve(true);
        this.onClose();
      } else {
        wx.showToast({
          title: '请输入必填字段',
          icon: 'none',
          position: 'bottom'
        })
        resolve(false)
      }
    },
    onInput(event) {
      const key = event.currentTarget.dataset.key,
        value = event.detail;
      this.setData({
        dialog: {
          ...this.data.dialog,
          [key]: value
        }
      })
    }
  },
  lifetimes: {
    attached() {
      this.fetchData();
      this.setData({
        beforeClose : (action)=>{
          return new Promise((resolve) => {
              if (action === 'confirm') {
                this.onConfirm(resolve);
              } else {
                // 拦截取消操作
                resolve(true);
                this.onClose();
              }
          });
        } 
      })
    }
  }
})